<?php

namespace App\Http\Controllers\BusinessData;

use App\Http\Conf\ResultInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Models\Business\InvoiceDetails;
use App\Http\Models\DistributionChannel;
use App\Http\Models\ProjectType;
use App\Http\Models\SalesOffice;
use App\Http\Models\SalesOrderType;
use App\Http\Models\SalesOrganization;
use App\Http\Models\SalesRegion;
use App\Http\Requests\Business\InvoiceDetailsRequest;
use App\Imports\InvoiceDetailsImport;
use App\Imports\SpecialOrderImport;
use Exception;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class InvoiceDetailsController extends Controller
{
    private $select_where = [];
    private $request_params = [
        'year' => '',
        'month' => '',
        'sales_order_no' => '',
    ];

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->dealRequestParams($request);

        $query = InvoiceDetails::where($this->select_where);
        if (isset($request->delete) && count($this->select_where) > 0) {
            $query->delete();
        }

        $amount_total_price_no_tax = $query->sum('total_price_no_tax');
        $models = $query->paginate(config('report.quantity_per_page'));

        return view('business_data.invoice_details.index', [
            'models' => $models,
            'amount_total_price_no_tax' => $amount_total_price_no_tax,
            'request_params' => $this->request_params,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $sales_order_types = SalesOrderType::all();
        $project_types = ProjectType::all();
        $sales_organizations = SalesOrganization::all();
        $sales_regions = SalesRegion::all();
        $distribution_channels = DistributionChannel::all();

        return view('business_data.invoice_details.create', [
            'sales_order_types' => $sales_order_types,
            'project_types' => $project_types,
            'sales_organizations' => $sales_organizations,
            'sales_regions' => $sales_regions,
            'distribution_channels' => $distribution_channels,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(InvoiceDetailsRequest $request)
    {
        $model = new InvoiceDetails();
        $model->year = $request->year;
        $model->month = $request->month;
        $model->sales_order_no = $request->sales_order_no;
        $model->sales_order_line_no = $request->sales_order_line_no;
        $model->material = $request->material;
        $model->quantity = $request->quantity;
        $model->total_price_tax_discount = $request->total_price_tax_discount;
        $model->total_price_tax = $request->total_price_tax;
        $model->total_price_no_tax = $request->total_price_no_tax;
        $model->tax = $request->tax;
        $model->discount = $request->discount;
        $model->surcharge = $request->surcharge;
        $model->sales_order_type_code = $request->sales_order_type_code;
        $model->project_type_code = $request->project_type_code;
        $model->sales_organization_code = $request->sales_organization_code;
        $model->sales_region_code = $request->sales_region_code;
        $model->sales_office_code = $request->sales_office_code;
        $model->distribution_channel_code = $request->distribution_channel_code;
        $model->payer_id = $request->payer_id;
        $model->salesman_id = $request->salesman_id;
        if ($model->save()) {
            return redirect()->action('BusinessData\InvoiceDetailsController@show', $model);
        } else {
            dd("添加数据有异常！");
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $model = InvoiceDetails::find($id);
        return view('business_data.invoice_details.show', ['model' => $model]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $model = InvoiceDetails::find($id);
        $sales_order_types = SalesOrderType::all();
        $project_types = ProjectType::all();
        $sales_organizations = SalesOrganization::all();
        $sales_regions = SalesRegion::all();
        $sales_offices = SalesOffice::where(['sales_region_code' => $model->sales_region_code])->get();
        $distribution_channels = DistributionChannel::all();
        return view('business_data.invoice_details.edit', [
            'model' => $model,
            'sales_order_types' => $sales_order_types,
            'project_types' => $project_types,
            'sales_organizations' => $sales_organizations,
            'sales_regions' => $sales_regions,
            'sales_offices' => $sales_offices,
            'distribution_channels' => $distribution_channels,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(InvoiceDetailsRequest $request, $id)
    {
        $model = InvoiceDetails::find($id);
        $model->year = $request->year;
        $model->month = $request->month;
        $model->sales_order_no = $request->sales_order_no;
        $model->sales_order_line_no = $request->sales_order_line_no;
        $model->material = $request->material;
        $model->quantity = $request->quantity;
        $model->total_price_tax_discount = $request->total_price_tax_discount;
        $model->total_price_tax = $request->total_price_tax;
        $model->total_price_no_tax = $request->total_price_no_tax;
        $model->tax = $request->tax;
        $model->discount = $request->discount;
        $model->surcharge = $request->surcharge;
        $model->sales_order_type_code = $request->sales_order_type_code;
        $model->project_type_code = $request->project_type_code;
        $model->sales_organization_code = $request->sales_organization_code;
        $model->sales_region_code = $request->sales_region_code;
        $model->sales_office_code = $request->sales_office_code;
        $model->distribution_channel_code = $request->distribution_channel_code;
        $model->payer_id = $request->payer_id;
        $model->salesman_id = $request->salesman_id;
        if ($model->save()) {
            return redirect()->action('BusinessData\InvoiceDetailsController@show', $model);
        } else {
            dd("编辑数据有异常！");
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $model = InvoiceDetails::find($id);
        if ($model->delete()) {
            return ['status' => ResultInfo::SUCCESS];
        } else {
            return ['status' => ResultInfo::UNKNOWN];
        }
    }


    //导入开票明细数据
    public function import(Request $request)
    {
        if ($request->method() == 'GET') {
            return view('business_data.invoice_details.import');
        } elseif ($request->method() == 'POST') {
            if ($request->upload_file == null) {
                return redirect()->back()->with('fail', '请选择文件');
            }

            try {
                Excel::import(new InvoiceDetailsImport, request()->file('upload_file'));
            } catch (Exception $e) {
                return redirect()->back()->with('fail', $e->getMessage());
            }
            return redirect()->action('BusinessData\InvoiceDetailsController@index')->with('success', '导入数据成功！');
        }
    }


    //导入特价订单
    public function importSpecialOrder(Request $request)
    {
        if ($request->method() == 'GET') {
            return view('business_data.invoice_details.import_special_order');
        } elseif ($request->method() == 'POST') {
            if ($request->upload_file == null) {
                return redirect()->back()->with('fail', '请选择文件');
            }

            try {
                Excel::import(new SpecialOrderImport, request()->file('upload_file'));
            } catch (Exception $e) {
                return redirect()->back()->with('fail', $e->getMessage());
            }
            return redirect()->action('BusinessData\InvoiceDetailsController@index')->with('success', '导入数据成功！');
        }
    }


    //根据物料数据更新订单的合同分类
    public function updateCategoryContract(Request $request)
    {
        $where['material.year'] = $request->year;
        $where['order.year'] = $request->year;
        $where['order.month'] = $request->month;

        $invoice_details = DB::table('invoice_details_sd002 as order')
            ->leftJoin('material', 'order.material', '=', 'material.material')
            ->select(['order.id', 'material.material', 'material.category_contract_id'])
            ->where($where)->get();
        foreach ($invoice_details as $value) {
            InvoiceDetails::where('id', $value->id)
                ->update(['category_contract_id' => $value->category_contract_id]);
        }
        return ['status' => ResultInfo::SUCCESS];
    }

    //根据物料数据，更新订单的是否特价
    public function updateSpecialOrderFromMaterial(Request $request)
    {
        $where['material.year'] = $request->year;
        $where['order.year'] = $request->year;
        $where['order.month'] = $request->month;
        $where['order.is_special'] = 0;

        $invoice_details = DB::table('invoice_details_sd002 as order')
            ->leftJoin('material', 'order.material', '=', 'material.material')
            ->select(['order.id', 'material.material', 'material.is_special_offer'])
            ->where($where)->get();

        foreach ($invoice_details as $value) {
            InvoiceDetails::where('id', $value->id)
                ->update(['is_special' => $value->is_special_offer]);
        }
        return ['status' => ResultInfo::SUCCESS];
    }

    /**
     * 处理请求参数
     */
    private function dealRequestParams(Request $request)
    {
        if (is_numeric($request->year)) {
            $this->select_where[] = ['year', $request->year];
            $this->request_params['year'] = $request->year;
        }

        if (is_numeric($request->month)) {
            $this->select_where[] = ['month', $request->month];
            $this->request_params['month'] = $request->month;
        }

        if ($request->sales_order_no != '') {
            $this->select_where[] = ['sales_order_no', $request->sales_order_no];
            $this->request_params['sales_order_no'] = $request->sales_order_no;
        }
    }
}
